package com.jian.java;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;

/**
 * @author Jiange
 * @create 2021-04-06-12:23
 */
public class MyServlet extends HttpServlet {
    @Override
    public void init() throws ServletException {
        super.init();
        System.out.println("第一个servlet");
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//        request.setCharacterEncoding("utf-8");
        System.out.println("请求的编码集为"+request.getCharacterEncoding());//null
        System.out.println(request.getParameter("name"));//李子建
//        response.setStatus(302); 不设置这个状态码 浏览器不会自动跳转
        //客户端重定向时 可以访问web工程外的资源、地址栏会改变、不能访问web-inf的资源、不共享request的域的数据
//        response.setHeader("location","http://localhost:8080/ge");
        response.sendRedirect("http://localhost:8080/ge");//直接设置了状态码不用自己设置
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        /**
         * ServletContext的作用
         * 1.获取web.xml上下文参数  context-param
         * 2.获取当前的工作路径
         * 3.获取工程部署后在服务器磁盘上的绝对路径
         * 4.像Map一样存取数据
         */
        ServletContext servletContext = getServletContext();
        String username = servletContext.getInitParameter("username");
        String contextPath = servletContext.getContextPath();
        String realPath = servletContext.getRealPath("/");
        System.out.println(username);
        System.out.println("contextPath = " + contextPath);//contextPath = /jiange
        System.out.println("realPath = " + realPath);//realPath = D:\WEB\JavaWeb\out\artifacts\02_servlet_war_exploded\

        servletContext.setAttribute("key1","value1");
        System.out.println("域数据key1"+servletContext.getAttribute("key1"));

        //HttpServletRequest
        System.out.println(request.getRequestURL());//http://localhost:8080/jiange/jian
        System.out.println(request.getRequestURI());///jiange/jian
        System.out.println(request.getRemoteHost());
        System.out.println(request.getHeader("accept"));
        System.out.println(request.getMethod());
        System.out.println(request.getParameter("name"));
        System.out.println(request.getParameter("password"));
        String[] hobbies = request.getParameterValues("hobby");
        System.out.println(Arrays.toString(hobbies));//[10, 20]


        /**
         * 请求转发可以访问web-inf文件夹 而且只能在当前的工程 不能访问百度子类的
         */
        request.setAttribute("key","value");
        RequestDispatcher requestDispatcher = request.getRequestDispatcher("ge");

        requestDispatcher.forward(request,response);

    }
}
